package org.al.poc.router;

import java.util.HashMap;

public class RoundRobin {
	
	private static int i = 1;
	private static HashMap<Long, Integer> sessionMap = new HashMap<Long, Integer>();
	
	private static WebServerInfo server1;
	private static WebServerInfo server2;
	
	
	public static void setServers(WebServerInfo server1, WebServerInfo server2) {

		server1.setServerIndex(1);
		server2.setServerIndex(2);
		RoundRobin.server1 = server1;
		RoundRobin.server2 = server2;
	}
	
	
	
	public static synchronized WebServerInfo getNextServer() {
		if (server1 == null || server2 == null) {
			return server1 != null ? server1 : server2;
		}
		
		if (i == 1) {
			i = 2;
			return server1;
		}
		
		i = 1;
		return server2;
		
	}
	
	
	public static void removeServer(int index) {
		if (index == 1) {
			if (server1 == null) return;
			synchronized (server1) {
				server1 = null;
			}
			LogManager.logserver1Down();
		}
		else {
			if (server2 == null) return;
			synchronized (server2) {
				server2 = null;
			}
			LogManager.logserver2Down();
		}
	}

	
	public static synchronized WebServerInfo getAssociatedServer(long sessionId) {
		
		if (server1 == null || server2 == null)
			return server1 != null ? server1 : server2;
		
		
		switch(sessionMap.get(sessionId)) {
		case 1:
			return server1 != null ? server1 : (server2 != null ? server2 : null);
		case 2:
			return server2 != null ? server2 : (server1 != null ? server1 : null);
		default : 
			return null;
		}
	}
	
	
	
	public static void setConnection(Long sessionId, WebServerInfo server) {
		synchronized (sessionMap) {
			sessionMap.put(sessionId, server.getServerIndex());
		}
	}

}
